// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/dwio/common/reader_factory.h>

namespace kumo::pollux::dwio::common {
    namespace {
        using ReaderFactoriesMap =
        melon::F14FastMap<FileFormat, std::shared_ptr<ReaderFactory> >;

        ReaderFactoriesMap &readerFactories() {
            static ReaderFactoriesMap factories;
            return factories;
        }
    } // namespace

    bool registerReaderFactory(std::shared_ptr<ReaderFactory> factory) {
        [[maybe_unused]] const bool ok =
                readerFactories().insert({factory->fileFormat(), factory}).second;
        // NOTE: re-enable this check after Prestissimo has updated dwrf registration.
#if 0
  POLLUX_CHECK(
      ok,
      "ReaderFactory is already registered for format {}",
      toString(factory->fileFormat()));
#endif
        return true;
    }

    bool unregisterReaderFactory(FileFormat format) {
        auto count = readerFactories().erase(format);
        return count == 1;
    }

    std::shared_ptr<ReaderFactory> getReaderFactory(FileFormat format) {
        auto it = readerFactories().find(format);
        POLLUX_CHECK(
            it != readerFactories().end(),
            "ReaderFactory is not registered for format {}",
            toString(format));
        return it->second;
    }
} // namespace kumo::pollux::dwio::common
